package com.nuo.modules.teacher.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nuo.common.excel.po.ExportListPo;
import com.nuo.common.utils.*;
import com.nuo.modules.poster.entity.PosterEntity;
import com.nuo.modules.poster.service.PosterService;
import com.nuo.modules.signRecord.entity.SignRecordEntity;
import com.nuo.modules.signRecord.service.SignRecordService;
import com.nuo.modules.student.po.PwdPo;
import com.nuo.modules.sys.entity.SysUserTokenEntity;
import com.nuo.modules.sys.service.ShiroService;
import com.nuo.modules.sys.service.SysUserTokenService;
import com.nuo.modules.teacher.entity.TeacherEntity;
import com.nuo.modules.teacher.po.LoginPo;
import com.nuo.modules.teacher.po.PosterPO;
import com.nuo.modules.teacher.po.ResetPO;
import com.nuo.modules.teacher.po.SignPo;
import com.nuo.modules.teacher.service.TeacherService;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 *
 *
 * @author nuo
 * @email 3033616351@qq.com
 * @date 2022-11-04 17:08:46
 */
@RestController
@RequestMapping("teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @Autowired
    SignRecordService signRecordService;

    @Autowired
    SysUserTokenService sysUserTokenService;
    @Autowired
    ShiroService shiroService;


    @Autowired
    PosterService posterService;

    @Autowired
    InfoUtils<TeacherEntity> infoUtils;

    /**
     * 登陆
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginPo po){
        return teacherService.login(po);
    }


    @GetMapping("/detail")
    public R info(@RequestParam String token){
        //根据accessToken，查询用户信息
        SysUserTokenEntity tokenEntity = shiroService.queryByToken(token);
        //token失效
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        SysUserTokenEntity one = sysUserTokenService.getOne(new LambdaQueryWrapper<SysUserTokenEntity>().eq(SysUserTokenEntity::getIdentity, 2).eq(SysUserTokenEntity::getToken, token));
        TeacherEntity teacher = teacherService.getById(one.getUserId());
        return R.ok().put("teacher", teacher);
    }

    /**
     * 发送动态信息
     */
    @PostMapping("/sendPoster")
    public R sendPoster(@RequestBody PosterPO po){
        String token = po.getToken();
        //根据accessToken，查询用户信息
        SysUserTokenEntity tokenEntity = shiroService.queryByToken(token);
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        SysUserTokenEntity one = sysUserTokenService.getOne(new LambdaQueryWrapper<SysUserTokenEntity>().eq(SysUserTokenEntity::getIdentity, 2).eq(SysUserTokenEntity::getToken, token));
        PosterEntity entity = BeanUtil.copyProperties(po, PosterEntity.class);
        entity.setTeacherId(one.getUserId());
        posterService.save(entity);
        return R.ok();
    }


    /**
     * 获取动态信息
     */
    @PostMapping("/getPoster")
    public R getPoster(@RequestBody PosterPO po){
        String token = po.getToken();
        //根据accessToken，查询用户信息
        SysUserTokenEntity tokenEntity = shiroService.queryByToken(token);
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        SysUserTokenEntity one = sysUserTokenService.getOne(new LambdaQueryWrapper<SysUserTokenEntity>().eq(SysUserTokenEntity::getIdentity, 2).eq(SysUserTokenEntity::getToken, token));
        List<PosterEntity> list = posterService.list(
                new LambdaQueryWrapper<PosterEntity>()
                        .eq(PosterEntity::getCategory, po.getCategory())
                        .eq(PosterEntity::getTeacherId, one.getUserId()).orderByDesc(PosterEntity::getCreateTime)
        );

        return R.ok().put("list",list);
    }


    //修改密码
    @PostMapping("/changePwd")
    public R changePwd(@RequestBody PwdPo po){

        //根据accessToken，查询用户信息
        SysUserTokenEntity tokenEntity = shiroService.queryByToken(po.getToken());
        //token失效
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            return R.error("token失效，请重新登录");
        }
        SysUserTokenEntity one = sysUserTokenService.getOne(new LambdaQueryWrapper<SysUserTokenEntity>().eq(SysUserTokenEntity::getIdentity, 2).eq(SysUserTokenEntity::getToken, po.getToken()));
        TeacherEntity teacher = teacherService.getById(one.getUserId());

        String oldPassword = new Sha256Hash(po.getOldPassword(), Constant.TSALT).toHex();
        String newPassword = new Sha256Hash(po.getNewPassword(), Constant.TSALT).toHex();

        if (!PwdUtils.isOk(po.getNewPassword())) {
            return R.error("密码需为数字+字母6位");
        }

        if (!Objects.equals(oldPassword, teacher.getPassword())) {
            return R.error("原密码输入有误...");
        }

        teacher.setPassword(newPassword);
        teacherService.updateById(teacher);
        return R.ok();
    }


    /**
     * 导入老师信息
     */
    @PostMapping("/importList")
    public R importList(@RequestParam("file") MultipartFile file){
        return teacherService.importList(file);
    }

    /**
     * 导出老师信息
     */
    @PostMapping("/exportList")
    public R exportList(@RequestBody ExportListPo<TeacherEntity> po){
        return teacherService.exportList(po);
    }

    /**
     * 导出全部老师信息
     */
    @RequestMapping("/exportAll")
    public R exportAll(){
        return teacherService.exportAll();
    }

    /**
     * 广场模块看视频认证老师信息
     */
    @PostMapping("/sign")
    public R sign(@RequestBody SignPo po, HttpServletRequest request){
        return teacherService.sign(po, request);
    }

    /**
     * 重置密码
     */
    @PostMapping("/resetPwd")
    public R resetPwd(@RequestBody ResetPO po){
        TeacherEntity teacher = new TeacherEntity();
        teacher.setId(po.getId());
        teacher.setPassword(Constant.T_PWD);
        teacherService.updateById(teacher);
        return R.ok();
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
        public R list(@RequestParam Map<String, Object> params){
        PageUtils page = teacherService.queryPage(params);

        return R.ok().put("page", page);
    }



    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
        public R info(@PathVariable("id") Long id){
		TeacherEntity teacher = teacherService.getById(id);
        return R.ok().put("teacher", teacher);
    }





    /**
     * 保存
     */
    @RequestMapping("/save")
        public R save(@RequestBody TeacherEntity teacher){
		teacherService.save(teacher);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
        public R update(@RequestBody TeacherEntity teacher){
		teacherService.updateById(teacher);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
        public R delete(@RequestBody Long[] ids){

        // 删除有关记录
        Long id=ids[0];
        TeacherEntity one = teacherService.getById(id);
        String teacherId = one.getTeacherId();

        signRecordService.remove(new LambdaQueryWrapper<SignRecordEntity>().eq(SignRecordEntity::getTeacherId,teacherId));
        posterService.remove(new LambdaQueryWrapper<PosterEntity>().eq(PosterEntity::getTeacherId,teacherId));


        teacherService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
